package cn.wmx.config;

import cn.wmx.io.Resources;
import cn.wmx.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 用于解析 configuration.xml
 * <p>
 * 抽风事件：这是为啥？？？
 * =================================
 * 如果导入maven依赖：dom4j 后，没有 SaxReader,
 * 手工引入 org.dom4j.io.SAXReader 包，
 * import org.dom4j.io.SAXReader;
 * =================================
 * C3P0 数据库连接池
 * import com.mchange.v2.c3p0.ComboPooledDataSource;
 * =================================
 */
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 将配置文件 configuration.xml 进行解析，封装成 Configuration 对象
     * 基于 dom4j
     *
     * @param inputStream
     * @return
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        // 解析 sqlMapConfig.xml 为 document 对象
        Document document = new SAXReader().read(inputStream);
        // <configuration>
        Element rootElement = document.getRootElement();
        // 数据库配置信息
        List<Element> list = rootElement.selectNodes("//property");
        // 解析数据库配置信息，组装到 properties 中 （key-value）
        Properties properties = new Properties();
        for (Element element : list) {
            // 获取标签中的属性值
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.put(name, value);
        }
        // 使用 C3P0 连接池，连接到数据库
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        this.configuration.setDataSource(comboPooledDataSource);

        // mapper.xml 解析：拿到路径 -> 字节输入流 -> dom4j 进行解析
        List<Element> mapperElementList = rootElement.selectNodes("//mapper");
        for (Element element : mapperElementList) {
            String mapperPath = element.attributeValue("resource");
            InputStream mapperInputStream = Resources.getResourceAsSteam(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(this.configuration);
            xmlMapperBuilder.parseMapper(mapperInputStream);
        }

        return configuration;
    }
}
